package com.j2205.hongzhiyuan.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    final static String path="mybatis.xml";
    static SqlSessionFactory sqlSessionFactory=null;
    static ThreadLocal<SqlSession> sessions = new ThreadLocal<>();
    static {
        InputStream ism=null;
        try {
            ism= Resources.getResourceAsStream(path);
            if(sqlSessionFactory==null){
                sqlSessionFactory=new SqlSessionFactoryBuilder().build(ism);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSession(){
        SqlSession s = sessions.get();
        if(s==null){
            s = sqlSessionFactory.openSession();
            sessions.set(s);
        }

        return s;
    }
    public static void commit(){
        SqlSession s = sessions.get();
        if(s!=null){
            s.commit();
        }
    }
    //    释放资源
    public static void  clseAll(){
        SqlSession s = sessions.get();
        sessions.set(null);
        if(s!=null){
            s.close();
        }
    }
}
